package cn.chencq.gdt.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpUtils {
	
	private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);
	 
	/**
	 * 返回请求状态码
	 * @param requestUrl
	 * @param proxy
	 * @return
	 */
	public static int getResponeCode(String requestUrl,Proxy proxy,String userAgent) {
		int responseCode = 0;
		HttpURLConnection conn = null; 
		try {
			URL url = new URL(requestUrl);
			// 打开和URL之间的连接
			if(proxy!=null){
				conn = (HttpURLConnection) url.openConnection(proxy);
			}else{
				conn=(HttpURLConnection) url.openConnection();
			}
			conn.setReadTimeout(5000);
			conn.setConnectTimeout(5000);
			// 设置通用的请求属性
			String host = Utils.getHost(requestUrl);
			
			String UserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 9_3_5 like Mac OS X) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/39.0.0.0 Mobile Safari/537.36";
			if(userAgent !=null){
				UserAgent = userAgent;
			}
			
			conn.setRequestMethod("GET");
			
			conn.setRequestProperty("Host", host);
			conn.setRequestProperty("User-Agent", UserAgent);
			
			conn.setInstanceFollowRedirects(true);
			conn.connect();
		
			responseCode = conn.getResponseCode();
		} catch (Exception e) {
			 
		} 
		return responseCode ;
	}
	
	/**
	 * 返回请求的结果
	 * @param requestUrl
	 * @param proxy
	 * @return
	 */
	public static String  getResponse(String requestUrl,Proxy proxy,String userAgent) {
		StringBuffer response = new StringBuffer();
		BufferedReader in = null;
		HttpURLConnection conn = null; 
		try {
			URL url = new URL(requestUrl);
			// 打开和URL之间的连接
			if(proxy!=null){
				conn = (HttpURLConnection) url.openConnection(proxy);
			}else{
				conn=(HttpURLConnection) url.openConnection();
			}
			conn.setReadTimeout(5000);
			conn.setConnectTimeout(5000);
			// 设置通用的请求属性
			String host = Utils.getHost(requestUrl);
			String UserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 9_3_5 like Mac OS X) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/39.0.0.0 Mobile Safari/537.36";
			if(userAgent !=null){
				UserAgent = userAgent;
			}
			conn.setRequestMethod("GET");
			
			conn.setRequestProperty("Host", host);
			conn.setRequestProperty("User-Agent", UserAgent);
			
			conn.setInstanceFollowRedirects(true);
			conn.connect();
		
			in= new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				response.append(line);
			}
		} catch (Exception e) {
			 
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
			}
		}
		
		return response.toString() ;
	}
	
	
}
